#! /usr/bin/env python
# -*- coding: utf-8 -*-

# Copyright (c) Huoty, All rights reserved
# Author: Huoty <sudohuoty@gmail.com>
# CreateTime: 2019-01-02 14:15:21

from sqlalchemy import Column, String, create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from decimal import Decimal as D
import sqlalchemy.types as types
from sqlalchemy import Integer


# 创建对象的基类:
Base = declarative_base()


class SqliteNumeric(types.TypeDecorator):

    impl = types.String

    def __init__(self, *arg, **kw):
        types.TypeDecorator.__init__(self, *arg, **kw)
        print("---", dir(self))

    def load_dialect_impl(self, dialect):
        return dialect.type_descriptor(types.VARCHAR(100))

    def process_bind_param(self, value, dialect):
        return str(value)

    def process_result_value(self, value, dialect):
        return D(value)


# can overwrite the imported type name
# @note: the TypeDecorator does not guarantie the scale and precision.
# you can do this with separate checks
Numeric = SqliteNumeric


class T(Base):

    __tablename__ = '_t'
    id = Column(Integer, primary_key=True, nullable=False, unique=True)
    value = Column(Numeric(12, 2), nullable=False)
    #value = Column(SqliteNumeric(12, 2), nullable=False)


def create_session(url):
    # 初始化数据库连接:
    engine = create_engine(url)
    # 初始化表结构
    Base.metadata.create_all(engine, checkfirst=True)
    # 创建DBSession类型:
    return sessionmaker(bind=engine)()


if __name__ == "__main__":
    session = create_session("sqlite:////home/huoty/temp/test.sqlite")
    t = T(id=1, value=1.23456)
    session.add(t)
    session.commit()

    t2 = session.query(T).filter(T.id==1).one()
    print("value type: %s, value: %s" % (type(t2.value), t2.value))

